package com.weiyuwqj.admin.controller.admin.invite;

import com.weiyuwqj.admin.controller.base.BaseController;
import com.weiyuwqj.admin.controller.admin.log.annotation.LogAnnotation;
import com.weiyuwqj.api.service.BusInvestRecordService;
import com.weiyuwqj.api.service.BasUserInviteService;
import com.weiyuwqj.api.service.SysNoticeTypeService;
import com.weiyuwqj.api.service.SysTempcodeService;
import com.weiyuwqj.api.service.SysUserService;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.model.SysNoticeType;
import com.weiyuwqj.api.model.SysTempcode;
import com.weiyuwqj.api.model.convert.InvestTypeConvert;
import com.weiyuwqj.api.model.convert.InviteAddtimeConvert;
import com.weiyuwqj.api.model.convert.ModelConvert;
import com.weiyuwqj.api.model.vo.BasUserInviteVo;
import com.weiyuwqj.api.model.vo.BusItemInvestVo;
import com.weiyuwqj.api.util.ExcelUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.RandomCodesUtils;
import com.weiyuwqj.api.util.Sms;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Yao xiuwei on 2015/12/2.
 */
@Controller
@RequestMapping(value = "/admin/invite")
public class BasUserInviteController extends BaseController {

    @Autowired
    BasUserInviteService userInviteService;

    @Autowired
    BusInvestRecordService recordService;

    @Autowired
    SysTempcodeService tempcodeService;

    @Autowired
    SysNoticeTypeService noticeTypeService;

    @Autowired
    SysUserService sysUserService;

    //显示&查询
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object list(Paginator paginator, HttpServletRequest request) {
        String username = request.getParameter("username");
        String realname = request.getParameter("realname");
        String mobile = request.getParameter("mobile");
        String beginDateTime = request.getParameter("beginDateTime");
        String endDateTime = request.getParameter("endDateTime");
        String inviteRealname = request.getParameter("inviteRealname");
        String inviteName = request.getParameter("inviteName");
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(username)) {
            map.put("username", username);
        }
        if (StringUtils.isNotEmpty(realname)) {
            map.put("realname", realname);
        }
        if (StringUtils.isNotEmpty(mobile)) {
            map.put("mobile", mobile);
        }
        if (StringUtils.isNotEmpty(beginDateTime)) {
            map.put("beginDateTime", beginDateTime);
        }
        if (StringUtils.isNotEmpty(endDateTime)) {
            map.put("endDateTime", endDateTime);
        }
        if (StringUtils.isNotEmpty(inviteRealname)) {
            map.put("inviteRealname", inviteRealname);
        }
        if (StringUtils.isNotEmpty(inviteName)) {
            map.put("inviteName", inviteName);
        }
        PageList list = userInviteService.getList(paginator, map);
        return list;
    }

    @ResponseBody
    @RequestMapping("/excel/invite")
    public Object userInvite(HttpServletRequest request,
                             String userId,
                             String username,
                             String realname,
                             String mobile,
                             String inviteRealname,
                             String inviteName,
                             String beginDateTime,
                             String endDateTime) {

        String[] cArray = {"邀请人ID", "邀请人", "真实姓名", "被邀请人ID", "被邀请人", "被邀请人用户名", "被邀请人手机", "注册时间", "添加IP"};
        String[] eArray = {"UserId", "Username", "Realname", "Id", "InviteRealname", "InviteUsername", "InviteMobile", "InviteUserAddtime", "Addip"};
        ModelConvert[] converts = {null, null, null, null, null, null, null, new InviteAddtimeConvert(), null};

        List<String> cList = Arrays.asList(cArray);
        List<String> eList = Arrays.asList(eArray);
        List<ModelConvert> convertList = Arrays.asList(converts);
        Map map = new HashMap();
        map.put("userId", userId);
        if (StringUtils.isNotEmpty(username)) {
            map.put("username", username);
        }
        if (StringUtils.isNotEmpty(mobile)) {
            map.put("mobile", mobile);
        }
        if (StringUtils.isNotEmpty(realname)) {
            map.put("realname", realname);
        }
        if (StringUtils.isNotEmpty(inviteName)) {
            map.put("invitename", inviteName);
        }
        if (StringUtils.isNotEmpty(inviteRealname)) {
            map.put("inviteRealname", inviteRealname);
        }
        if (StringUtils.isNotEmpty(beginDateTime)) {
            map.put("beginDateTime", beginDateTime);
        }
        if (StringUtils.isNotEmpty(endDateTime)) {
            map.put("endDateTime", endDateTime);
        }

        List<BasUserInviteVo> contentList = userInviteService.getList(map);

        String serverDir = request.getServletContext().getRealPath("/") + "admin/export/";
        String excelFilePath = ExcelUtils.export("邀请列表", cList, eList, convertList, contentList, serverDir);
        HashMap ret = Message.OK;
        ret.put("file", "export/" + excelFilePath);
        return ret;
    }


    //根据userId获取被邀请人列表
    @ResponseBody
    @RequestMapping(value = "/getListByUserId", method = RequestMethod.POST)
    public Object getListByUserId(Paginator paginator, Integer userId) {
        return userInviteService.getListByUserId(paginator, userId);
    }

    //根据inviteId获取邀请人信息
    @ResponseBody
    @RequestMapping(value = "/getOneByInviteId", method = RequestMethod.POST)
    public Object getOneByInviteId(Integer inviteId) {
        BasUserInviteVo basUserInviteVo = userInviteService.getOneByInviteId(inviteId);
        return basUserInviteVo;
    }

    /**
     * 根据userId获取投资列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getInvestListByUserId", method = RequestMethod.POST)
    public Object getInvestListByUserId(Paginator paginator, HttpServletRequest request) {
        String userId = request.getParameter("userId");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        return recordService.getList(paginator, map);
    }


    @ResponseBody
    @RequestMapping("/excel/inviteInvest")
    public Object inviteInvest(String userId, HttpServletRequest request) {

        String[] cArray = {"用户名", "投资状态", "投资金额(元)", "投资项目"};
        String[] eArray = {"Username", "InvestType", "InvestDealAmount", "ItemName"};
        ModelConvert[] converts = {null, new InvestTypeConvert(), null, null};

        List<String> cList = Arrays.asList(cArray);
        List<String> eList = Arrays.asList(eArray);
        List<ModelConvert> convertList = Arrays.asList(converts);
        Map map = new HashMap();
        map.put("userId", userId);
        List<BusItemInvestVo> contentList = recordService.getList(map);

        String serverDir = request.getServletContext().getRealPath("/") + "admin/export/";
        String excelFilePath = ExcelUtils.export("用户投资列表", cList, eList, convertList, contentList, serverDir);
        HashMap ret = Message.OK;
        ret.put("file", "export/" + excelFilePath);
        return ret;
    }


    /**
     * 修改邀请人
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modifyInvite", method = RequestMethod.POST)
    @LogAnnotation(module = "邀请管理/邀请列表", description = "修改邀请人")
    public Object modifyInvite(HttpServletRequest request) {

        String userId = request.getParameter("userId");
        String inviteId = request.getParameter("inviteId");
        String checkCode = request.getParameter("inputRandomCode");
        String mobile = noticeTypeService.getMobile();
        //获取系统验证码
        String verifyCode = this.getSessionValidCode();
        Date validPhoneExpiredTime = (Date) this.getSession().getAttribute("validPhoneExpiredTime");

        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime.getTime()) / 1000;

        Map map = new HashMap();
        if (between > com.weiyuwqj.api.constant.Constants.VALIDATETIME) {
            map.put("result", "fail");
            map.put("messageText", "验证码过期");
            map.put("messageCode", "admin.invite.randomCode.timeout");
            return map;
        }
        SysTempcode tempcode = tempcodeService.getByMobileAndCode(mobile, verifyCode);
        if (tempcode == null) {
            map.put("result", "fail");
            map.put("messageText", "您输入的验证码有误");
            map.put("messageCode", "admin.invite.validCode.error");
            return map;
        }
        if (!verifyCode.equalsIgnoreCase(checkCode)) {
            map.put("result", "fail");
            map.put("messageText", "您输入的验证码有误");
            map.put("messageCode", "admin.invite.validCode.error");
            return map;
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", userId);
        param.put("inviteId", inviteId);
        userInviteService.modifyInvite(param);
        return Message.OK;
    }

    //修改邀请人短信
    @ResponseBody
    @RequestMapping(value = "/inviteSendSms")
    @LogAnnotation(module = "邀请管理/邀请列表", description = "修改邀请人短信")
    public Object inviteSendSms() {

        String vaildPhoneCode = RandomCodesUtils.createRandom(true, 6);
        String mobile = noticeTypeService.getMobile();
        SysTempcode tempcode = new SysTempcode();
        Date now = new Date();
        tempcode.setAddtime(now);
        tempcode.setAddip(IpUtils.get());
        tempcode.setCode(vaildPhoneCode);
        tempcode.setMobile(mobile);
        tempcodeService.save(tempcode);
        this.getSession().setAttribute("verifyCode", vaildPhoneCode);
        this.getSession().setAttribute("validPhoneExpiredTime", now);
        SysNoticeType noticeType = noticeTypeService.getNoticeTypeByNid(Constants.modifyinvite_sms);
        return smsInfo(vaildPhoneCode, mobile, noticeType.getTypeContent(), now);
    }

    public Object smsInfo(String vaildPhoneCode, String mobile, String content, Date sendTime) {
        String randomCode = vaildPhoneCode;
        System.out.println("您的验证码：" + randomCode);
        content = content.replace(Constants.VALIDATECODE, randomCode);

        Map smsMap = new HashMap();
        smsMap.put("msgText", content);
        smsMap.put("mobile", mobile);
        String smsResponse = Sms.send(mobile, content).toString();

        Map ret = new HashMap();
        if (smsResponse.equals("发送成功")) {
            ret.put("result", "success");
            ret.put("validPhoneExpiredTime", sendTime);
        } else {
            ret.put("result", "fail");
            ret.put("message", smsResponse);
        }
        return ret;
    }
}
